<?php

declare(strict_types=1);

namespace App\Controller\Backend;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;

abstract class AbstractController
{

    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;

    protected LoggerInterface $logger;

    public function __construct()
    {
        try {
            $this->logger = $this->container->get(LoggerFactory::class)->get('api', 'backend');
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
        }
    }

    /**
     * API返回.
     */
    protected function apiReturn(int $code = 200, string $msg = 'succ', array $data = []): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->json([
            'code' => $code == 200 ? 0 : $code,
            'msg' => $msg,
            'count' => $data['total'] ?? 0,
            'data' => $data['records'] ?? $data,
        ]);
    }
}
